package com.qf.user.controller;

import com.qf.base.controller.BaseController;
import com.qf.base.dto.file.ImgDTO;
import com.qf.base.dto.file.ZoomDTO;
import com.qf.base.dto.sms.SmsDTO;
import com.qf.base.result.R;
import com.qf.base.util.JwtUtil;
import com.qf.base.util.SnowFlakeUtil;
import com.qf.base.vo.UserVO;
import com.qf.user.client.FileClient;
import com.qf.user.client.SmsClient;
import com.qf.user.dto.SignInDTO;
import com.qf.user.exception.SignInIsLockedException;
import com.qf.user.exception.SignInNameUnknownException;
import com.qf.user.exception.SignInPasswordErrorException;
import com.qf.user.exception.base.UserException;
import com.qf.user.model.User;
import com.qf.user.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.Random;

/**
 * @author 汤奇
 * @version V1.0
 * @Project BookPro
 * @Package com.qf.user.controller
 * @Description:
 * @Date 2022/7/29 20:42
 */
@RestController
@RequestMapping("qf/user")
public class UserController extends BaseController {

    @Resource
    private SnowFlakeUtil snowFlakeUtil;

    @Resource
    private SmsClient smsClient;

    @Resource
    private UserService userService;

    @Resource
    private FileClient fileClient;

    @GetMapping("test")
    public R test(HttpServletRequest request){

        //拿到前端传递过来的token
//        String token = request.getHeader("token");
//        System.out.println(token);

        return R.ok("我认识你").setResult("user",user()).setResult("userID",userId());
    }

    @PostMapping("signIn")
    public R signIn(@RequestBody SignInDTO signInDTO){
        String signInName = signInDTO.getSignInName();
        String password = signInDTO.getPassword();

        //业务逻辑-登录流程图
        System.out.println(signInName+":"+password);

        User user = userService.isLocked(signInName);
        if (user == null){
            return R.error(503,"该账户不存在!");
        }
        if (user.getIsLock() == 1){
            return R.error(501,"该账户已被锁定");
        }

        try {
            user = userService.signIn(signInName, password);
        } catch (SignInNameUnknownException e){
            return R.error(503,e.getMessage());

        } catch (SignInPasswordErrorException e){
            return R.error(502,e.getMessage());

        } catch (SignInIsLockedException e){
            return R.error(501,e.getMessage());

        } catch (UserException e) {
            return R.error(504,e.getMessage());
        }
        //签发token
        UserVO userVO = new UserVO();
        //复制成员的方法, 成员名相同就复制它们的内容
        BeanUtils.copyProperties(user,userVO);
        //把对象的密码清空
        userVO.setPassword("");
        String token = JwtUtil.generatorToken(userVO);

        return R.ok("登录成功")
                .setResult("token",token)
                .setResult("user",userVO);
    }

    /**
     * 短信验证码登录
     */
    @PostMapping("sendSms")
    public R sendSms(@RequestBody SmsDTO smsDTO){
        smsDTO.setTypeId(1);
        //验证码随机
        Random random = new Random();
        String code = "";
        for (int i = 0; i < 6; i++) {
            code += random.nextInt(10);
        }
        smsDTO.setCode(code);
        R sendResult = smsClient.send(smsDTO);
        return sendResult;
    }

    @PostMapping("smsSignIn")
    public R smsSignIn(@RequestBody SmsDTO smsDTO){
        smsDTO.setTypeId(1);
        R checkResult = smsClient.check(smsDTO);
        if (checkResult.isOk()){
            User user = userService.findOrSIgnUp(smsDTO.getPhone());

            //签发token
            UserVO userVO = new UserVO();
            //复制成员的方法.成员名相同就复制他们的内容
            BeanUtils.copyProperties(user,userVO);
            //把表示对象的密码清空
            userVO.setPassword("");
            String token = JwtUtil.generatorToken(userVO);

            return R.ok("登录成功")
                    .setResult("token",token)
                    .setResult("user",userVO);
        } else {
            return checkResult;
        }
    }

    /**
     * 上传头像的接口
     */
    @PostMapping("icon")
    public R icon(@RequestBody ImgDTO imgDTO) throws Exception {
        //1.获取用户id
        Long userId = userId();
        String base64 = imgDTO.getBase64();

        //将图片缩放
        ZoomDTO zoomDTO = new ZoomDTO();
        zoomDTO.setBase64(base64);
        zoomDTO.setHeight(150);
        zoomDTO.setWidth(150);
        R zoomResult = fileClient.zoom(zoomDTO);
        String url = (String) ((Map)zoomResult.getResult()).get("url");

        //更新数据库
        int result = userService.updateIconByUserId(userId, url);
        if (result == 1){
            return R.ok("更新成功");
        } else {
            return R.error("更新失败");
        }
    }
}
